#!/bin/bash -e

LOCALPATH=$(dirname "$(readlink -fm "$0")")
TOOLPATH=${LOCALPATH}/tools/Linux_Upgrade_Tool/
LOADER="${LOCALPATH}/bin/rk33/MiniLoaderAll.bin"
PARAMETER="${LOCALPATH}/parameter_gpt_linux.txt"
CHIP=""
DEVICE=""
IMAGE=""
DEVICE=""
SEEK=""

PATH=$PATH:$TOOLPATH

source $LOCALPATH/partitions.sh

usage() {
	echo -e "\nUsage:"
	echo -e "emmc:    $0 -c rk3288  -p system -i <image>"
	echo -e "sdcard:  $0 -c rk3288  -d </dev/sdX> -p system  -i <image>"
	echo -e "rockusb: $0 -p system  -i <image> \n"
}

finish() {
	echo -e "\e[31m FLASH IMAGE FAILED.\e[0m"
	exit -1
}
trap finish ERR

while getopts "c:t:s:d:p:r:d:i:h" flag; do
	case $flag in
		c)
			CHIP="$OPTARG"
			;;
		d)
			DEVICE="$OPTARG"
			;;
		i)
			IMAGE="$OPTARG"
			if [ ! -f "${IMAGE}" ]; then
				echo -e "\e[31m CAN'T FIND IMAGE \e[0m"
				usage
				exit
			fi
			;;
		p)
			PARTITIONS="$OPTARG"
			BPARTITIONS=$(echo $PARTITIONS | tr 'a-z' 'A-Z')
			SEEK=${BPARTITIONS}_START
			eval SEEK=\$$SEEK

			if [ -n "$(echo $SEEK | sed -n "/^[0-9]\+$/p")" ]; then
				echo "PARTITIONS OFFSET: $SEEK sectors."
			else
				echo -e "\e[31m INVAILD PARTITION.\e[0m"
				exit
			fi
			;;
	esac
done

if [ ! $IMAGE ]; then
	usage
	exit
fi

flash_upgt() {

	# Burn loader
	$TOOLPATH/upgrade_tool ul $LOADER

	sleep 1

	# Erase u-boot environment partition
	# FIXME
	dd if=/dev/zero of=raw.bin bs=1K count=0 seek=1
	echo "Erasing u-boot environment partition..."
	$TOOLPATH/upgrade_tool wl 8128 raw.bin
	rm raw.bin

	# Burn image
	echo "Burning image..."
	$TOOLPATH/upgrade_tool wl ${SEEK} ${IMAGE}

	# Burn GPT
	echo "Burning GPT..."
	$TOOLPATH/upgrade_tool di -p $PARAMETER

	# Reset
	$TOOLPATH/upgrade_tool rd
}

flash_sdcard() {
	pv -tpreb ${IMAGE} | sudo dd of=${DEVICE} seek=${SEEK} conv=notrunc
	sync
}

if [ ! $DEVICE ]; then
	flash_upgt
else
	flash_sdcard
fi
